﻿using System;
using System.IO;
using SilenthinkContract;
using System.ServiceModel;
using System.Configuration;
using SilenthinkContract.Component;

namespace SilenthinkService
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)]
    public class UploadService : IUploadService
    {
        /// <summary>
        /// 默认根目录
        /// </summary>
        private static readonly string RootFolder = ConfigurationManager.AppSettings["upload.rootfolder"] ?? "d:\\upload\\";
        /// <summary>
        /// 默认文件夹
        /// </summary>
        private static readonly string DefaultFolder = ConfigurationManager.AppSettings["upload.defaultfolder"] ?? "default";
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="uploadFile">待上传文件</param>
        public void UploadFile(UploadFileInfo uploadFile)
        {
            if (!uploadFile.Data.CanRead)
            {
                throw new Exception("数据流不可读!");
            }

            var folder = uploadFile.Folder;
            var fileName = uploadFile.Name;

            if (folder == null) folder = DefaultFolder;
            if (!folder.EndsWith("\\")) folder += "\\";

            var uploadFolder = RootFolder + folder;

            CreateFolder(uploadFolder);

            var filePath = Path.Combine(uploadFolder, fileName);

            SaveFile(filePath, uploadFile.Data);
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="folder">文件夹名</param>
        private static void CreateFolder(string folder)
        {
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
        }
        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="file">文件名(包含路径)</param>
        /// <param name="stream">文件数据流</param>
        private static void SaveFile(string file, Stream stream)
        {
            using (stream)
            using (var target = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                int count;
                const int bufferLen = 32768 * 2;//初始化一个64k的缓存
                var buffer = new byte[bufferLen];
                while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
                {
                    target.Write(buffer, 0, count);
                }
            }
        }
    }
}